<?php
/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 氚云API数据同步 - 同步氚云数据到本地批量接口
 * 尊重劳动成果是一种美德
 */

session_start();

// 检查登录状态
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

// 引入配置文件和客户端类
require_once '../config.php';
require_once '../classes/H3OpenApiClient.php';

header('Content-Type: application/json');

try {
    $config = require '../config.php';
    $client = new H3OpenApiClient($config);
    
    $syncCount = 0;
    $batchSize = 100;
    $currentBatch = 0;
    
    do {
        $fromRowNum = $currentBatch * $batchSize;
        $toRowNum = $fromRowNum + $batchSize - 1;
        
        $filter = [
            'FromRowNum' => $fromRowNum,
            'ToRowNum' => $toRowNum
        ];
        
        $result = $client->loadBizObjects($config['schema_code'], $filter);
        
        if (!empty($result)) {
            // 这里可以添加数据处理逻辑，比如保存到数据库
            $syncCount += count($result);
            $currentBatch++;
        }
        
    } while (!empty($result) && count($result) == $batchSize);
    
    echo json_encode([
        'success' => true,
        'message' => '同步完成',
        'sync_count' => $syncCount,
        'batch_count' => $currentBatch
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => '同步失败: ' . $e->getMessage()
    ]);
}
?>